package com.darren.euc.action;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.darren.euc.entity.ContractProduct;
import com.darren.euc.entity.PageBean;
import com.darren.euc.entity.ResponseJSON;
import com.darren.euc.entity.Room;
import com.darren.euc.entity.User;
import com.darren.euc.service.ContractProductService;
import com.darren.euc.service.RoomService;
import com.darren.euc.util.PropertyHelper;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/room")
public class RoomAction {
	
	private static final Logger log = Logger.getLogger(RoomAction.class);
	
	@Autowired
    private RoomService roomService;
	
	@Autowired
    private ContractProductService contractProductService;
	
	@ResponseBody
    @RequestMapping(value = "/list")//,method = RequestMethod.POST)
    public List<Room> getAllFunctions(HttpServletRequest request,HttpServletResponse response) {
    	List<Room> rooms = roomService.getAll();    	
        return rooms;
    }
	
	@ResponseBody
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public ResponseJSON queryRoom(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {	
		ResponseJSON responseJson = new ResponseJSON();
		PageBean pageBean = roomService.queryForPageUseHQL(requestJson.getJSONObject("data"), PropertyHelper.getRoomSize(), requestJson.getInt("currentPage"));
		responseJson.setData(pageBean);
		return responseJson;
    }
	
	@ResponseBody
    @RequestMapping(value = "/member_room",method = RequestMethod.POST)
    public List<Room> queryRoomByClientAndSpaceId(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {	
		Integer clientId = requestJson.getInt("clientId");
		Integer spaceId = requestJson.getInt("spaceId");		
		List<Room> rooms = roomService.getRoomByClientAndSpaceId(clientId,spaceId);
		for(Room room:rooms){
			room.setRoomType(null);
			room.setProvince(null);
			room.setCity(null);
			room.setSpace(null);
			room.setCreateUser(null);
			room.setLastModifyUser(null);
		}
        return rooms;
    }
	
	@ResponseBody
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ResponseJSON saveRoom(@RequestBody Room room,HttpServletRequest request,HttpServletResponse response) {	
		ResponseJSON responseJson = new ResponseJSON();
		try {
			User user = (User) request.getAttribute("user");
			room.setCreateUser(user);
			room.setCreateTime(new Date());
			room.setLastModifyUser(user);
			room.setLastModifyTime(new Date());
			room = roomService.save(room);
			responseJson.setStatus(0);
			responseJson.setMessage("添加成功！");
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-1);
			responseJson.setMessage("添加失败！");
		}
		responseJson.setData(room);
		System.out.println("==============================================================");
		System.out.println(responseJson.toString());
		System.out.println("==============================================================");
		return responseJson;
    }
	
	@ResponseBody
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public ResponseJSON deleteRole(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {
    	ResponseJSON responseJson = new ResponseJSON();
    	JSONObject jsonData = new JSONObject();
    	responseJson.setData(jsonData);
    	try{
    		Integer id = Integer.parseInt(requestJson.getString("id"));
    		List<ContractProduct> contractProducts = contractProductService.findByRoomId(id);
    		if(!CollectionUtils.isEmpty(contractProducts)){
				responseJson.setStatus(-1);
				responseJson.setMessage("不能删除已出粗的房间！");
				return responseJson;
			}
    		Room room = new Room();
    		room.setId(id);
    		roomService.delete(room);
        	responseJson.setStatus(0);
    		responseJson.setMessage("删除成功！");
    	}catch(Exception ex){
    		log.info(ex.getMessage(),ex);
        	responseJson.setStatus(-1);
    		responseJson.setMessage("删除失败！");
    	}
    	System.out.println("==============================================================");
    	System.out.println(requestJson.toString());
    	System.out.println(responseJson.toString());
    	System.out.println("==============================================================");
        return responseJson;
    }
	  
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ResponseJSON updateRoom(@RequestBody Room room, HttpServletRequest request,
			HttpServletResponse response) {
		ResponseJSON responseJson = new ResponseJSON();
		try {
			User user = (User) request.getAttribute("user");
			if(user != null){
				room.setLastModifyUser(user);
				
			}
			if(!room.isEnable()){//等于删除
				List<ContractProduct> contractProducts = contractProductService.findByRoomId(room.getId());
				if(!CollectionUtils.isEmpty(contractProducts)){
					responseJson.setStatus(-1);
					responseJson.setMessage("不能删除已出粗的房间！");
					return responseJson;
				}
			}

			room.setLastModifyTime(new Date());
			room = roomService.update(room);			
			responseJson.setStatus(0);
			responseJson.setMessage("保存成功！");
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-1);
			responseJson.setMessage("保存失败！");
		}
		responseJson.setData(room);
		System.out.println("==============================================================");
		System.out.println(responseJson.toString());
		System.out.println("==============================================================");
		return responseJson;
	}

	@ResponseBody
	@RequestMapping(value = "/availableroom", method = RequestMethod.POST)
	public ResponseJSON queryAvaliableRoom(@RequestBody JSONObject requestJson, HttpServletRequest request,
			HttpServletResponse response) {
		ResponseJSON responseJson = new ResponseJSON();
		try {
			Integer spaceId = requestJson.getInt("spaceId");
			String roomName = requestJson.getString("roomName");
			String rentStart = requestJson.getString("rentStart");
			String rentEnd = requestJson.getString("rentEnd");
			List<Room> rooms = roomService.queryAvaliableRoom(spaceId,roomName,"1900-01-01","1900-01-02");
			List<Room> avaliableRooms = roomService.queryAvaliableRoom(spaceId,roomName,rentStart,rentEnd);
			if(rooms != null && rooms.size() > 0){
				if(avaliableRooms != null && avaliableRooms.size() > 0){
					responseJson.setData(avaliableRooms);
				}else{					
					List<ContractProduct> contractProducts =contractProductService.queryContractProducts(spaceId,roomName,rentStart,rentEnd);
					if(contractProducts != null && contractProducts.size()> 0){
						ContractProduct contractProduct = contractProducts.get(0);
						responseJson.setStatus(-4);
						SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); 
						responseJson.setMessage(String.format("当前空间的房间【%s】,在【%s】到【%s】时间段已被租赁，请选择其它房间或者时间段！",roomName,format.format(contractProduct.getRentStart()),format.format(contractProduct.getRentEnd())));
					}else{
						responseJson.setStatus(-3);
						responseJson.setMessage("未找到有效的房间，请核对房间名！");
					}
				}				
			}else{
				responseJson.setStatus(-2);
				responseJson.setMessage(String.format("当前空间不存在房间【%s】！",roomName));
			}
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-1);
			responseJson.setMessage("查询房间失败！");
		}
		return responseJson;
	}
	
	@ResponseBody
	@RequestMapping(value = "/detail", method = RequestMethod.POST)
	public ResponseJSON getUsedDetail(@RequestBody JSONObject requestJson, HttpServletRequest request,
			HttpServletResponse response) {
		ResponseJSON responseJson = new ResponseJSON();
		try {			
			Integer roomId = requestJson.getInt("roomId");			
			Map<String,Object> usedDetail  = roomService.getUsedDetail(roomId);
			responseJson.setData(usedDetail);
			responseJson.setStatus(0);
			responseJson.setMessage("获取成功！");
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-1);
			responseJson.setMessage("获取失败！");
		}		
		System.out.println("==============================================================");
		System.out.println(responseJson.toString());
		System.out.println("==============================================================");
		return responseJson;
	}
	
}